/*
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-02 09:54:42
 * @LastEditTime: 2024-02-04 11:19:02
 */
import path from 'path-browserify'
import { paramType } from 'iking-utils'
import Clipboard from 'clipboard'

export function resolveRoutePath(basePath: string, routePath?: string) {
  return basePath ? path.resolve(basePath, routePath ?? '') : routePath ?? ''
}

export const copyText = async (text: string) => {
  try {
    if (navigator && 'clipboard' in navigator) {
      await navigator.clipboard.writeText(text)
    }
    else {
      const input = document.createElement('textarea')
      input.value = text
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
    }
    return true
  }
  catch (error) {
    return false
  }
}

export const isNotEmpty = (obj: string | null | undefined) => {
  return (obj !== undefined && obj !== null && obj !== '' && obj !== 'null')
}

/**
 * 把 src 属性的值赋给 tar 的同名属性
 * @param {*} tar 目标对象
 * @param {*} src 源对象
 */
export const copyValue = (tar: any, src: any) => {
  if (!paramType.isObject(tar) || !paramType.isObject(src))
    throw new Error('参数异常')

  Object.keys(tar).forEach(key => {
    if (Reflect.has(src, key))
      tar[key] = src[key]
  })
}

/**
 * 将内容复制到剪贴板
 * @param content
 * @param clickEvent
 * @param $message
 * @param successMsg
 * @param errorMsg
 */
export const copyToClipboard = (content: any, clickEvent: any, $message: any, successMsg: any, errorMsg: any) => {
  const clipboard: any = new Clipboard(clickEvent.target, {
    text: () => content
  })

  clipboard.on('success', () => {
    $message.success(successMsg)
    clipboard.destroy()
  })

  clipboard.on('error', () => {
    $message.error(errorMsg)
    clipboard.destroy()
  })

  clipboard.onClick(clickEvent)
}
